<?php

namespace app\service;

use app\model\ArticleCategory;

class ArticleCategoryService
{
    private $articleCategory;

    public function __construct()
    {
        $this->articleCategory = new ArticleCategory();
    }

    public function list($params = [])
    {
        $page = $params['page'] ?? 1;
        $pageSize = $params['pageSize'] ?? 10;
        $where = [];

        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }

        if (isset($params['status']) && $params['status'] !== '') {
            $where[] = ['status', '=', $params['status']];
        }

        $result = $this->articleCategory->where($where)
            ->order(['sort' => 'desc', 'id' => 'asc'])
            ->paginate([
                'list_rows' => $pageSize,
                'page' => $page
            ])->append(['status_text']);

        return $result;
    }

    public function save($param)
    {
        if(isset($param['id'])) unset($param['id']);
        return $this->articleCategory->allowField(['name', 'status', 'sort'])->create($param);
    }

    public function update($id, $param)
    {
        $articleCategory = $this->articleCategory->find($id);
        return $articleCategory->allowField(['name', 'status', 'sort'])->save($param);
    }

    public function delete($id)
    {
        return $this->articleCategory->destroy($id);
    }

    public function getAll($param = [])
    {
        $where = [];

        if (isset($param['status']) && $param['status'] !== '') {
            $where[] = ['status', '=', 1];
            return $this->articleCategory->where($where)
                ->order(['sort' => 'desc', 'id' => 'asc'])
                ->field('name,id')
                ->select();
        } else {
            return $this->articleCategory->order(['sort' => 'desc', 'updated_at'=>'desc','id' => 'desc'])
                ->withTrashed()
                ->field('name,id')
                ->select();
        }
    }
}
